package org.redis.cluster.auth;

import org.redis.cluster.RedisCluster;
import org.redis.cluster.plugin.Plugin;
import org.redis.cluster.processor.CommandProcessor;
import org.redis.cluster.redis.RedisCommand;
import org.redis.cluster.redis.transport.RedisReply;
import org.redis.cluster.redis.transport.reply.RedisErrorReply;
import org.redis.cluster.redis.transport.reply.RedisStatusReply;
import org.redis.cluster.transport.session.Session;

public class AuthCommandProcessor implements Plugin,CommandProcessor {
	
	private RedisCluster redisCluster;
	private String password;
	
	@Override
	public void init(RedisCluster redisCluster) {
		this.redisCluster=redisCluster;
		this.password=initPassword();
	}
	
	@Override
	public void destroy() {
	}
	
	protected String initPassword() {
		return AuthHelper.getPassword(redisCluster);
	}
	
	@Override
	public RedisReply process(RedisCommand command, Session session) {
		if(command.getParameterCount()==1) {
			return new RedisErrorReply("ERR invalid password");
		}
		
		String password=new String(command.getParameters()[1]);
		if(!password.equals(this.password)) {
			return new RedisErrorReply("ERR invalid password");
		}
		
		AuthHelper.setAuth(session, password);
		return new RedisStatusReply("OK");
	}

	@Override
	public String getSupportCommand() {
		return AuthConstants.COMMAND;
	}
	
	public void setRedisCluster(RedisCluster redisCluster) {
		this.redisCluster = redisCluster;
	}
	public RedisCluster getRedisCluster() {
		return redisCluster;
	}

}